<template>
  <div class="refund-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>退款管理</span>
          <el-button-group>
            <el-button type="primary" @click="exportRefunds"
              >导出数据</el-button
            >
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单号"
            clearable
          />
        </el-form-item>
        <el-form-item label="退款状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="待处理" value="pending" />
            <el-option label="商家处理中" value="merchant_processing" />
            <el-option label="商家拒绝" value="merchant_rejected" />
            <el-option label="待管理员审核" value="admin_review" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="orderNo" label="订单号" min-width="180" />
        <el-table-column prop="productInfo" label="商品信息" min-width="200">
          <template #default="{ row }">
            <div class="product-info">
              <div class="product-name">{{ row.productName }}</div>
              <div class="product-type">
                {{ getProductType(row.productType) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="refundAmount"
          label="退款金额"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span class="amount">¥{{ row.refundAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="applyTime"
          label="申请时间"
          width="180"
          sortable="custom"
        />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleDetail(row)">
                详情
              </el-button>
              <el-button
                v-if="row.status === 'admin_review'"
                type="warning"
                size="small"
                @click="openAuditDialog(row)"
              >
                审核
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无退款数据" 
              :image-size="200"
            >
              <div class="empty-text">暂无退款申请</div>
              <div class="empty-subtext">用户申请退款后将在此处显示</div>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="退款详情"
      width="1000px"
      destroy-on-close
      class="refund-detail-dialog"
    >
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <div class="detail-section">
            <h4>订单信息</h4>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="订单号" :span="2">{{
                currentDetail.orderNo
              }}</el-descriptions-item>
              <el-descriptions-item label="下单时间">{{
                currentDetail.orderTime
              }}</el-descriptions-item>
              <el-descriptions-item label="商品名称" :span="2">{{
                currentDetail.productName
              }}</el-descriptions-item>
              <el-descriptions-item label="商品类型">
                <el-tag>{{ getProductType(currentDetail.productType) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="订单金额">
                <span class="amount">¥{{ currentDetail.orderAmount }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="支付方式">{{
                currentDetail.paymentMethod
              }}</el-descriptions-item>
              <el-descriptions-item label="支付时间">{{
                currentDetail.payTime
              }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="detail-section">
            <h4>退款信息</h4>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="退款单号" :span="2">{{
                currentDetail.refundNo
              }}</el-descriptions-item>
              <el-descriptions-item label="申请时间">{{
                currentDetail.applyTime
              }}</el-descriptions-item>
              <el-descriptions-item label="申请退款金额">
                <span class="amount">¥{{ currentDetail.refundAmount }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="退款类型">{{
                currentDetail.refundType
              }}</el-descriptions-item>
              <el-descriptions-item label="当前状态">
                <el-tag :type="getStatusType(currentDetail.status)">
                  {{ getStatusLabel(currentDetail.status) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="detail-section">
            <h4>联系信息</h4>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="用户姓名">{{
                currentDetail.userName
              }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{
                currentDetail.userPhone
              }}</el-descriptions-item>
              <el-descriptions-item label="电子邮箱">{{
                currentDetail.userEmail
              }}</el-descriptions-item>
              <el-descriptions-item label="商家名称">{{
                currentDetail.merchantName
              }}</el-descriptions-item>
              <el-descriptions-item label="商家电话">{{
                currentDetail.merchantPhone
              }}</el-descriptions-item>
              <el-descriptions-item label="商家邮箱">{{
                currentDetail.merchantEmail
              }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>

        <!-- 退款申请 -->
        <el-tab-pane label="退款申请" name="apply">
          <div class="detail-section">
            <h4>申请详情</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="退款原因">
                <el-tag size="small">{{ currentDetail.refundReason }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="详细说明">
                <div class="detail-content">
                  {{ currentDetail.refundDescription }}
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="退款规则">
                <div
                  class="detail-content"
                  v-html="currentDetail.refundPolicy"
                ></div>
              </el-descriptions-item>
              <el-descriptions-item
                label="凭证图片"
                v-if="currentDetail.evidenceImages?.length"
              >
                <div class="image-list">
                  <div
                    v-for="(img, index) in currentDetail.evidenceImages"
                    :key="index"
                    class="image-item"
                  >
                    <el-image
                      :src="img"
                      :preview-src-list="currentDetail.evidenceImages"
                      class="evidence-image"
                      fit="cover"
                    >
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div class="image-title">凭证 {{ index + 1 }}</div>
                  </div>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>

        <!-- 商家处理 -->
        <el-tab-pane label="商家处理" name="merchant">
          <div class="detail-section" v-if="currentDetail.merchantResponse">
            <h4>处理详情</h4>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="处理结果">
                <el-tag
                  :type="
                    currentDetail.merchantResponse.isAgreed
                      ? 'success'
                      : 'danger'
                  "
                >
                  {{
                    currentDetail.merchantResponse.isAgreed
                      ? "同意退款"
                      : "拒绝退款"
                  }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="处理人">{{
                currentDetail.merchantResponse.processor
              }}</el-descriptions-item>
              <el-descriptions-item label="处理时间">{{
                currentDetail.merchantResponse.processTime
              }}</el-descriptions-item>
              <el-descriptions-item label="处理说明">
                <div class="detail-content">
                  {{ currentDetail.merchantResponse.comment }}
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="退款条款">
                <div
                  class="detail-content"
                  v-html="currentDetail.merchantResponse.terms"
                ></div>
              </el-descriptions-item>
              <el-descriptions-item
                label="相关凭证"
                v-if="currentDetail.merchantResponse.evidenceImages?.length"
              >
                <div class="image-list">
                  <div
                    v-for="(img, index) in currentDetail.merchantResponse
                      .evidenceImages"
                    :key="index"
                    class="image-item"
                  >
                    <el-image
                      :src="img"
                      :preview-src-list="
                        currentDetail.merchantResponse.evidenceImages
                      "
                      class="evidence-image"
                      fit="cover"
                    >
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div class="image-title">凭证 {{ index + 1 }}</div>
                  </div>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <el-empty v-else description="暂无商家处理信息" />
        </el-tab-pane>

        <!-- 处理记录 -->
        <el-tab-pane label="处理记录" name="history">
          <div class="detail-section">
            <el-timeline>
              <el-timeline-item
                v-for="(record, index) in currentDetail.processHistory"
                :key="index"
                :timestamp="record.time"
                :type="getTimelineItemType(record.type)"
                :hollow="record.type === 'system'"
              >
                <div class="timeline-content">
                  <div class="timeline-header">
                    <span class="timeline-title">{{ record.title }}</span>
                    <el-tag
                      size="small"
                      :type="getOperatorType(record.operator.type)"
                    >
                      {{ record.operator.name }}
                    </el-tag>
                  </div>
                  <div class="timeline-detail">{{ record.content }}</div>
                  <div
                    class="timeline-attachments"
                    v-if="record.attachments?.length"
                  >
                    <div class="attachment-list">
                      <div
                        v-for="(attachment, idx) in record.attachments"
                        :key="idx"
                        class="attachment-item"
                      >
                        <el-link :href="attachment.url" target="_blank">
                          <el-icon><Document /></el-icon>
                          {{ attachment.name }}
                        </el-link>
                      </div>
                    </div>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>

        <!-- 备注记录 -->
        <el-tab-pane label="备注记录" name="notes">
          <div class="detail-section">
            <div class="notes-header">
              <h4>备注记录</h4>
              <el-button type="primary" size="small" @click="addNote">
                添加备注
              </el-button>
            </div>
            <div class="notes-list">
              <div
                v-for="(note, index) in currentDetail.notes"
                :key="index"
                class="note-item"
              >
                <div class="note-header">
                  <span class="note-author">{{ note.author }}</span>
                  <span class="note-time">{{ note.time }}</span>
                </div>
                <div class="note-content">{{ note.content }}</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
            v-if="currentDetail.status === 'admin_review'"
            type="primary"
            @click="openAuditDialog(currentDetail)"
          >
            处理退款
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="'退款处理 - ' + currentDetail.orderNo"
      width="800px"
      destroy-on-close
      class="audit-dialog"
    >
      <el-form
        ref="formRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="100px"
        class="audit-form"
      >
        <div class="form-section">
          <h4>订单信息</h4>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="商品名称">{{
              currentDetail.productName
            }}</el-descriptions-item>
            <el-descriptions-item label="订单金额"
              >¥{{ currentDetail.orderAmount }}</el-descriptions-item
            >
            <el-descriptions-item label="申请退款"
              >¥{{ currentDetail.refundAmount }}</el-descriptions-item
            >
            <el-descriptions-item label="退款原因">{{
              currentDetail.refundReason
            }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="form-section">
          <h4>处理意见</h4>
          <el-form-item label="处理结果" prop="result" required>
            <el-radio-group v-model="auditForm.result">
              <el-radio label="approved">同意退款</el-radio>
              <el-radio label="rejected">拒绝退款</el-radio>
              <el-radio label="partial">部分退款</el-radio>
            </el-radio-group>
          </el-form-item>

          <template
            v-if="
              auditForm.result === 'approved' || auditForm.result === 'partial'
            "
          >
            <el-form-item label="退款金额" prop="amount" required>
              <el-input-number
                v-model="auditForm.amount"
                :min="0"
                :max="currentDetail.orderAmount"
                :precision="2"
                :step="10"
                style="width: 200px"
              />
              <span class="form-tip"
                >最大可退 ¥{{ currentDetail.orderAmount }}</span
              >
            </el-form-item>

            <el-form-item label="退款方式" prop="refundMethod" required>
              <el-select v-model="auditForm.refundMethod" style="width: 200px">
                <el-option label="原路退回" value="original" />
                <el-option label="退款到余额" value="balance" />
                <el-option label="人工处理" value="manual" />
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="处理说明" prop="comment" required>
            <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入处理说明（至少10个字符）"
            />
          </el-form-item>

          <el-form-item label="相关政策" prop="policy">
            <el-input
              v-model="auditForm.policy"
              type="textarea"
              :rows="3"
              placeholder="请输入相关退款政策说明"
            />
          </el-form-item>

          <el-form-item label="处理凭证">
            <el-upload
              class="evidence-uploader"
              :action="uploadAction"
              :file-list="auditForm.evidenceImages"
              list-type="picture-card"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              multiple
            >
              <template #default>
                <el-icon><Plus /></el-icon>
                <div class="upload-text">上传图片</div>
              </template>
              <template #file="{ file }">
                <div class="upload-item">
                  <img :src="file.url" class="upload-image" />
                  <div class="upload-actions">
                    <el-icon @click="handlePreview(file)"><ZoomIn /></el-icon>
                    <el-icon @click="handleRemove(file)"><Delete /></el-icon>
                  </div>
                </div>
              </template>
            </el-upload>
            <div class="upload-tip">
              支持jpg、png格式，单个文件不超过2M，最多可上传5张
            </div>
          </el-form-item>
        </div>

        <div class="form-section">
          <h4>其他信息</h4>
          <el-form-item label="处理人" required>
            <el-input
              v-model="auditForm.processor"
              disabled
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="处理时间">
            <el-input
              v-model="auditForm.processTime"
              disabled
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="auditForm.note"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息（选填）"
            />
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit" :loading="submitting"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 添加备注对话框 -->
    <el-dialog
      v-model="noteDialogVisible"
      title="添加备注"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="noteFormRef"
        :model="noteForm"
        :rules="noteRules"
        label-width="80px"
      >
        <el-form-item label="备注内容" prop="content">
          <el-input
            v-model="noteForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入备注内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="noteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNote">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog v-model="previewVisible" title="图片预览">
      <img :src="previewUrl" alt="Preview" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Picture, ZoomIn, Delete } from "@element-plus/icons-vue";
import axios from "@/api/axios";
import * as XLSX from "xlsx";

// 搜索表单
const searchForm = reactive({
  orderNo: "",
  status: "",
  dateRange: [],
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 详情对话框
const detailDialogVisible = ref(false);
const currentDetail = ref({});

// 标签页相关
const activeTab = ref("basic");

// 表单相关
const formRef = ref(null);
const noteFormRef = ref(null);
const submitting = ref(false);

// 备注对话框
const noteDialogVisible = ref(false);
const noteForm = reactive({
  content: "",
});

const noteRules = {
  content: [
    { required: true, message: "请输入备注内容", trigger: "blur" },
    { min: 5, message: "备注内容不能少于5个字符", trigger: "blur" },
  ],
};

// 审核对话框
const auditDialogVisible = ref(false);
const auditForm = reactive({
  result: "approved",
  amount: 0,
  refundMethod: "original",
  comment: "",
  policy: "",
  evidenceImages: [],
  processor: "管理员",
  processTime: new Date().toLocaleString(),
  note: "",
});

// 图片预览
const previewVisible = ref(false);
const previewUrl = ref("");

// 审核表单验证规则
const auditRules = {
  result: [{ required: true, message: "请选择处理结果", trigger: "change" }],
  amount: [{ required: true, message: "请输入退款金额", trigger: "blur" }],
  refundMethod: [
    { required: true, message: "请选择退款方式", trigger: "change" },
  ],
  comment: [
    { required: true, message: "请输入处理说明", trigger: "blur" },
    { min: 10, message: "说明不能少于10个字符", trigger: "blur" },
  ],
};

// 获取商品类型标签
const getProductType = (type) => {
  const types = {
    ticket: "门票",
    hotel: "酒店",
    experience: "体验",
    product: "文创商品",
  };
  return types[type] || type;
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    pending: "待处理",
    merchant_processing: "商家处理中",
    merchant_rejected: "商家拒绝",
    admin_review: "待管理员审核",
    approved: "已通过",
    rejected: "已拒绝",
    cancelled: "已取消",
  };
  return statusMap[status] || status;
};

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: "info",
    merchant_processing: "warning",
    merchant_rejected: "danger",
    admin_review: "warning",
    approved: "success",
    rejected: "danger",
    cancelled: "info",
  };
  return typeMap[status] || "info";
};

// 获取时间线项目类型
const getTimelineItemType = (type) => {
  const typeMap = {
    apply: "info",
    merchant_process: "warning",
    admin_process: "success",
    reject: "danger",
    cancel: "info",
  };
  return typeMap[type] || "info";
};

// 获取操作者类型样式
const getOperatorType = (type) => {
  const typeMap = {
    user: "info",
    merchant: "warning",
    admin: "success",
    system: "",
  };
  return typeMap[type] || "";
};

// 处理详情查看
const handleDetail = async (row) => {
  try {
    loading.value = true;
    // 获取退款详情
    const response = await axios.get(`/admin/refunds/${row.id}`);
    
    // 检查是否有详情返回
    if (response) {
      currentDetail.value = response;
    } else {
      // 使用模拟详情数据
      currentDetail.value = {
        ...row,
        // 模拟更多详细信息
        id: row.id,
        orderNo: row.orderNo || "DD202403150001",
        refundNo: row.refundNo || "TK202403150001",
        orderTime: row.orderTime || "2024-03-15 08:00:00",
        payTime: row.payTime || "2024-03-15 08:05:00",
        paymentMethod: row.paymentMethod || "微信支付",
        orderAmount: row.orderAmount || 299,
        refundAmount: row.refundAmount || 299,
        refundType: row.refundType || "订单取消",
        refundReason: row.refundReason || "行程变更",
        refundDescription: row.refundDescription || "因个人原因需要改期，但未能及时联系商家",
        refundPolicy: row.refundPolicy || `
          <p>1. 未使用的门票，提前24小时取消可全额退款</p>
          <p>2. 提前12小时取消收取10%手续费</p>
          <p>3. 12小时内取消收取30%手续费</p>
          <p>4. 过期未使用不予退款</p>
        `,
        evidenceImages: row.evidenceImages || [
          "https://example.com/evidence1.jpg",
          "https://example.com/evidence2.jpg",
        ],
        userName: row.userName || "张三",
        userPhone: row.userPhone || "13800138000",
        userEmail: row.userEmail || "zhangsan@example.com",
        merchantName: row.merchantName || "贵港古镇旅游有限公司",
        merchantPhone: row.merchantPhone || "0775-1234567",
        merchantEmail: row.merchantEmail || "service@example.com",
        merchantResponse: row.merchantResponse || {
          isAgreed: false,
          processor: "李经理",
          comment: "根据预订规则，该订单已超过可退款时间",
          processTime: "2024-03-15 14:30:00",
          terms: `
            <p>根据《门票预订服务协议》第三条规定：</p>
            <p>1. 本产品为预售门票，不支持无理由退款</p>
            <p>2. 需至少提前24小时申请退款</p>
            <p>3. 如遇特殊情况，需提供相关证明</p>
          `,
          evidenceImages: ["https://example.com/merchant-evidence.jpg"],
        },
        processHistory: row.processHistory || [
          {
            type: "apply",
            title: "用户提交退款申请",
            content: "申请退款金额：¥299",
            time: "2024-03-15 10:00:00",
            operator: {
              type: "user",
              name: "用户",
            },
          },
          {
            type: "merchant_process",
            title: "商家处理",
            content: "商家拒绝退款：根据预订规则，该订单已超过可退款时间",
            time: "2024-03-15 14:30:00",
            operator: {
              type: "merchant",
              name: "商家",
            },
            attachments: [
              {
                name: "服务协议.pdf",
                url: "https://example.com/agreement.pdf",
              },
            ],
          },
          {
            type: "admin_process",
            title: "等待管理员审核",
            content: "退款申请已提交至管理员进行审核",
            time: "2024-03-15 14:35:00",
            operator: {
              type: "system",
              name: "系统",
            },
          },
        ],
        notes: row.notes || [
          {
            author: "客服小王",
            time: "2024-03-15 11:00:00",
            content: "已电话联系用户，了解具体情况",
          },
          {
            author: "运营主管",
            time: "2024-03-15 14:00:00",
            content: "请商家根据实际情况处理",
          },
        ],
      };
    }
  } catch (error) {
    console.error("获取退款详情失败：", error);
    // 使用传入的行数据
    currentDetail.value = {
      ...row,
      // 模拟更多详细信息
      orderNo: "DD202403150001",
      refundNo: "TK202403150001",
      orderTime: "2024-03-15 08:00:00",
      payTime: "2024-03-15 08:05:00",
      paymentMethod: "微信支付",
      orderAmount: 299,
      refundAmount: 299,
      refundType: "订单取消",
      refundReason: "行程变更",
      refundDescription: "因个人原因需要改期，但未能及时联系商家",
      refundPolicy: `
        <p>1. 未使用的门票，提前24小时取消可全额退款</p>
        <p>2. 提前12小时取消收取10%手续费</p>
        <p>3. 12小时内取消收取30%手续费</p>
        <p>4. 过期未使用不予退款</p>
      `,
      evidenceImages: [
        "https://example.com/evidence1.jpg",
        "https://example.com/evidence2.jpg",
      ],
      userName: "张三",
      userPhone: "13800138000",
      userEmail: "zhangsan@example.com",
      merchantName: "贵港古镇旅游有限公司",
      merchantPhone: "0775-1234567",
      merchantEmail: "service@example.com",
      merchantResponse: {
        isAgreed: false,
        processor: "李经理",
        comment: "根据预订规则，该订单已超过可退款时间",
        processTime: "2024-03-15 14:30:00",
        terms: `
          <p>根据《门票预订服务协议》第三条规定：</p>
          <p>1. 本产品为预售门票，不支持无理由退款</p>
          <p>2. 需至少提前24小时申请退款</p>
          <p>3. 如遇特殊情况，需提供相关证明</p>
        `,
        evidenceImages: ["https://example.com/merchant-evidence.jpg"],
      },
      processHistory: [
        {
          type: "apply",
          title: "用户提交退款申请",
          content: "申请退款金额：¥299",
          time: "2024-03-15 10:00:00",
          operator: {
            type: "user",
            name: "用户",
          },
        },
        {
          type: "merchant_process",
          title: "商家处理",
          content: "商家拒绝退款：根据预订规则，该订单已超过可退款时间",
          time: "2024-03-15 14:30:00",
          operator: {
            type: "merchant",
            name: "商家",
          },
          attachments: [
            {
              name: "服务协议.pdf",
              url: "https://example.com/agreement.pdf",
            },
          ],
        },
        {
          type: "admin_process",
          title: "等待管理员审核",
          content: "退款申请已提交至管理员进行审核",
          time: "2024-03-15 14:35:00",
          operator: {
            type: "system",
            name: "系统",
          },
        },
      ],
      notes: [
        {
          author: "客服小王",
          time: "2024-03-15 11:00:00",
          content: "已电话联系用户，了解具体情况",
        },
        {
          author: "运营主管",
          time: "2024-03-15 14:00:00",
          content: "请商家根据实际情况处理",
        },
      ],
    };
  } finally {
    loading.value = false;
    detailDialogVisible.value = true;
  }
};

// 打开审核对话框
const openAuditDialog = (row) => {
  currentDetail.value = row;
  Object.assign(auditForm, {
    result: "approved",
    amount: row.refundAmount,
    refundMethod: "original",
    comment: "",
    policy: "",
    evidenceImages: [],
    processor: "管理员",
    processTime: new Date().toLocaleString(),
    note: "",
  });
  auditDialogVisible.value = true;
};

// 提交审核
const submitAudit = () => {
  if (!formRef.value) return;

  formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 构建审核数据
        const data = {
          id: currentDetail.value.id,
          result: auditForm.result,
          amount: auditForm.amount,
          refundMethod: auditForm.refundMethod,
          comment: auditForm.comment,
          policy: auditForm.policy,
          evidenceImages: auditForm.evidenceImages.map(item => item.url),
          note: auditForm.note
        };
        
        // 调用审核API
        await axios.post("/admin/refunds/audit", data);

        const result =
          auditForm.result === "approved"
            ? "通过"
            : auditForm.result === "partial"
              ? "部分退款"
              : "拒绝";

        ElMessage.success(`退款申请审核${result}成功`);
        auditDialogVisible.value = false;
        handleSearch();
      } catch (error) {
        console.error("审核失败：", error);
        ElMessage.error("审核失败");
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 图片上传相关
const uploadAction = "/api/admin/upload";

const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

const handleUploadSuccess = (response, file) => {
  auditForm.evidenceImages.push({
    name: file.name,
    url: response.url,
  });
};

const handlePreview = (file) => {
  previewUrl.value = file.url;
  previewVisible.value = true;
};

const handleRemove = (file) => {
  const index = auditForm.evidenceImages.findIndex(
    (item) => item.url === file.url,
  );
  if (index !== -1) {
    auditForm.evidenceImages.splice(index, 1);
  }
};

// 搜索相关方法
const handleSearch = async () => {
  loading.value = true;
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      orderNo: searchForm.orderNo || undefined,
      status: searchForm.status || undefined,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : undefined,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : undefined,
      sortField: sortConfig.prop,
      sortOrder: sortConfig.order,
    };

    // 调用API获取数据
    const response = await axios.get("/admin/refunds", { params });
    
    // 检查响应是否存在
    if (response) {
      // 不管是否有数据，都使用后端返回的结果
      tableData.value = Array.isArray(response.records) ? response.records : [];
      total.value = response.total || 0;
    } else {
      // 响应对象不存在，设置为空数组
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取退款列表失败：", error);
    ElMessage.error("获取数据失败");
    
    tableData.value = [
      {
        id: 1,
        orderNo: "R202403150001",
        refundNo: "RF20240315001",
        productName: "贵港古镇门票",
        productType: "ticket",
        orderAmount: 299,
        refundAmount: 299,
        status: "admin_review",
        applyTime: "2024-03-15 10:00:00",
        orderTime: "2024-03-14 15:30:00",
        payTime: "2024-03-14 15:35:00",
        paymentMethod: "微信支付",
        refundType: "未使用",
        reason: "行程变更",
        reasonDetail: "因公司安排临时出差，无法按原计划出行",
        evidenceImages: [
          "https://example.com/evidence1.jpg",
          "https://example.com/evidence2.jpg"
        ],
        userName: "张三",
        userPhone: "13800138000",
        userEmail: "zhangsan@example.com",
        merchantName: "贵港古镇旅游有限公司",
        merchantPhone: "0775-1234567",
        merchantEmail: "service@example.com"
      },
      {
        id: 2,
        orderNo: "R202403120002",
        refundNo: "RF20240312001",
        productName: "贵港石蟆风景区套票",
        productType: "ticket",
        orderAmount: 450,
        refundAmount: 450,
        status: "approved",
        applyTime: "2024-03-12 09:15:00",
        orderTime: "2024-03-10 14:20:00",
        payTime: "2024-03-10 14:25:00",
        paymentMethod: "支付宝",
        refundType: "未使用",
        reason: "天气原因",
        reasonDetail: "景区因暴雨临时关闭，无法游览",
        evidenceImages: [
          "https://example.com/evidence3.jpg",
          "https://example.com/evidence4.jpg"
        ],
        userName: "李四",
        userPhone: "13900139000",
        userEmail: "lisi@example.com",
        merchantName: "贵港市旅游发展有限公司",
        merchantPhone: "0775-7654321",
        merchantEmail: "contact@example.com",
        processHistory: [
          {
            type: "apply",
            title: "用户提交退款申请",
            content: "申请退款金额：¥450",
            time: "2024-03-12 09:15:00",
            operator: {
              type: "user",
              name: "用户",
            },
          },
          {
            type: "merchant_process",
            title: "商家处理",
            content: "商家同意退款：景区确实因暴雨临时关闭",
            time: "2024-03-12 11:30:00",
            operator: {
              type: "merchant",
              name: "商家",
            }
          },
          {
            type: "admin_process",
            title: "管理员审核",
            content: "管理员通过退款申请",
            time: "2024-03-12 14:20:00",
            operator: {
              type: "admin",
              name: "管理员-王主管",
            }
          },
          {
            type: "refund_complete",
            title: "退款完成",
            content: "退款金额450元已原路退回支付宝账户",
            time: "2024-03-12 15:00:00",
            operator: {
              type: "system",
              name: "系统",
            }
          }
        ]
      },
      {
        id: 3,
        orderNo: "R202403080003",
        refundNo: "RF20240308001",
        productName: "贵港美食文化体验",
        productType: "experience",
        orderAmount: 688,
        refundAmount: 344,
        status: "merchant_processing",
        applyTime: "2024-03-08 16:45:00",
        orderTime: "2024-03-05 10:10:00",
        payTime: "2024-03-05 10:15:00",
        paymentMethod: "银联支付",
        refundType: "部分使用",
        reason: "质量问题",
        reasonDetail: "部分项目与介绍不符，体验感较差",
        evidenceImages: [
          "https://example.com/evidence5.jpg",
          "https://example.com/evidence6.jpg",
          "https://example.com/evidence7.jpg"
        ],
        userName: "王五",
        userPhone: "13700137000",
        userEmail: "wangwu@example.com",
        merchantName: "贵港传统美食协会",
        merchantPhone: "0775-8765432",
        merchantEmail: "food@example.com",
        processHistory: [
          {
            type: "apply",
            title: "用户提交退款申请",
            content: "申请退款金额：¥344",
            time: "2024-03-08 16:45:00",
            operator: {
              type: "user",
              name: "用户",
            }
          }
        ]
      },
      {
        id: 4,
        orderNo: "R202403010004",
        refundNo: "RF20240301001",
        productName: "贵港市博物馆专题展览",
        productType: "exhibition",
        orderAmount: 120,
        refundAmount: 120,
        status: "rejected",
        applyTime: "2024-03-01 11:30:00",
        orderTime: "2024-02-28 09:45:00",
        payTime: "2024-02-28 09:50:00",
        paymentMethod: "微信支付",
        refundType: "未使用",
        reason: "其他原因",
        reasonDetail: "临时有事无法前往",
        evidenceImages: [],
        userName: "赵六",
        userPhone: "13600136000",
        userEmail: "zhaoliu@example.com",
        merchantName: "贵港市博物馆",
        merchantPhone: "0775-9876543",
        merchantEmail: "museum@example.com",
        processHistory: [
          {
            type: "apply",
            title: "用户提交退款申请",
            content: "申请退款金额：¥120",
            time: "2024-03-01 11:30:00",
            operator: {
              type: "user",
              name: "用户",
            }
          },
          {
            type: "merchant_process",
            title: "商家处理",
            content: "商家拒绝退款：根据预订规则，展览票不支持临时原因退款",
            time: "2024-03-01 14:20:00",
            operator: {
              type: "merchant",
              name: "商家",
            },
            attachments: [
              {
                name: "预订须知.pdf",
                url: "https://example.com/booking-notes.pdf",
              }
            ]
          },
          {
            type: "admin_process",
            title: "管理员审核",
            content: "管理员拒绝退款：符合商家规定，不予退款",
            time: "2024-03-02 10:15:00",
            operator: {
              type: "admin",
              name: "管理员-李经理",
            }
          }
        ]
      }
    ];
    total.value = tableData.value.length;
  } finally {
    loading.value = false;
  }
};

const resetSearch = () => {
  Object.assign(searchForm, {
    orderNo: "",
    status: "",
    dateRange: [],
  });
  handleSearch();
};

// 导出数据
const exportRefunds = () => {
  // 制作导出数据
  const exportData = tableData.value.map(item => {
    return {
      '订单号': item.orderNo,
      '商品名称': item.productName,
      '商品类型': getProductType(item.productType),
      '退款金额': `¥${item.refundAmount}`,
      '退款状态': getStatusLabel(item.status),
      '申请时间': item.applyTime
    };
  });

  // 创建工作簿
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "退款数据");
  
  // 设置列宽
  const colWidth = [
    { wch: 15 }, // 订单号
    { wch: 20 }, // 商品名称
    { wch: 10 }, // 商品类型
    { wch: 10 }, // 退款金额
    { wch: 12 }, // 退款状态
    { wch: 20 }, // 申请时间
  ];
  worksheet['!cols'] = colWidth;
  
  // 导出文件
  const now = new Date();
  const fileName = `退款数据_${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}.xlsx`;
  XLSX.writeFile(workbook, fileName);
  
  ElMessage.success("导出成功");
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 排序相关
const sortConfig = reactive({
  prop: "",
  order: "",
});

const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
  handleSearch();
};

// 添加备注
const addNote = () => {
  noteForm.content = "";
  noteDialogVisible.value = true;
};

// 提交备注
const submitNote = () => {
  if (!noteFormRef.value) return;

  noteFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 构建备注数据
        const data = {
          refundId: currentDetail.value.id,
          content: noteForm.content
        };
        
        // 调用添加备注API
        await axios.post("/admin/refunds/note", data);

        // 更新备注列表
        currentDetail.value.notes.unshift({
          author: "管理员",
          time: new Date().toLocaleString(),
          content: noteForm.content,
        });

        ElMessage.success("添加备注成功");
        noteDialogVisible.value = false;
      } catch (error) {
        console.error("添加备注失败：", error);
        ElMessage.error("添加备注失败");
      }
    }
  });
};

// 初始化
onMounted(() => {
  handleSearch();
});
</script>

<style scoped>
.refund-management {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  background-color: var(--el-bg-color);
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-weight: 500;
}

.product-type {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.amount {
  font-weight: 500;
  color: var(--el-color-danger);
}

.detail-section {
  margin-top: 24px;
}

.detail-section h4 {
  margin: 0 0 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid var(--el-border-color-light);
  color: var(--el-text-color-primary);
}

.evidence-image {
  width: 100px;
  height: 100px;
  margin-right: 8px;
  border-radius: 4px;
  cursor: pointer;
}

.timeline-content {
  padding: 8px;
}

.timeline-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.timeline-detail {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.pagination-container {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-descriptions) {
  margin-bottom: 16px;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  max-width: 90vw;
  width: 800px !important;
}

:deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__footer) {
  padding: 20px;
  margin: 0;
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 表单区域样式 */
.form-section {
  background-color: var(--el-fill-color-blank);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.form-section h4 {
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--el-border-color-light);
  color: var(--el-text-color-primary);
  font-weight: 500;
}

/* 上传区域样式 */
.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}

.upload-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.upload-item {
  position: relative;
  width: 120px;
  height: 120px;
}

.upload-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.upload-actions {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  gap: 4px;
  padding: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 0 4px 0 4px;
}

.upload-actions .el-icon {
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.upload-actions .el-icon:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .refund-management {
    padding: 12px;
  }

  .search-form {
    padding: 16px;
  }

  :deep(.el-dialog) {
    width: 90% !important;
  }

  .form-section {
    padding: 15px;
  }

  .upload-item {
    width: 100px;
    height: 100px;
  }
}

.approval-action {
  padding-top: 16px;
  text-align: center;
}

.empty-state {
  padding: 40px 0;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
